<?php
declare (strict_types = 1);
namespace app\api\controller;
use app\api\BaseController;
// use app\api\middleware\Auth;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Request;
// 支付1 参考：https://pay.yansongda.cn/docs/v3/wechat/pay.html
use Yansongda\Pay\Pay;
use Yansongda\Pay\Contract\HttpClientInterface;
// 支付2  参考：v2+v3 https://packagist.org/packages/wechatpay/wechatpay
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use zjkal\TimeHelper;//调用时间库
class Pays extends BaseController
{
	protected $middleware = [
    	
    ];
	// 退款订单
	public function refund(){
		//支付配置
		$config=payconfig();
		Pay::config($config);
		$orderid= request()->param('orderid');//获取订单4200002627202504214325481058
		$order = [
		    'out_trade_no' => '20250421141550083418837',
		    'out_refund_no' => '4200002627202504214325481058',
			// 'transaction_id'=>    '4200002627202504214325481058',
		    'amount' => [
		        'refund' => 5*100,//退款金额
		        'total' => 5*100,//订单金额
		        'currency' => 'CNY',//币种
		    ],
		    '_action' => 'mini', // 小程序退款
		
		];
		// echo '1';exit;
		$result = Pay::wechat()->refund($order);
		return json(['code'=>200,'msg'=>'退款成功','data'=>$result]);
	}
	public function notify_refund(){
		$config=payconfig();
		Pay::config($this->config); 
		 try{
		    $data = Pay::wechat()->callback(); // 是的，验签就这么简单！
		    } catch (\Throwable $e) {
		    // dd($e);
			return  json(['code'=>400,'msg'=>'退款失败','data'=>$e]);
		}  
		return Pay::wechat()->success();
	}
	public function seleorder(){
		$openid= request()->param('openid');//获取订单
		$config=payconfig();
		
		Pay::config($config);
		$order = [
		    'out_trade_no' => $openid,
		    // '_action' => 'jsapi', // 默认为 jsapi
		    // '_action' => 'app', // 查询 App 支付
		    // '_action' => 'h5', // 查询 H5 支付
		    // '_action' => 'mini', // 查询小程序支付
		    // '_action' => 'native', // 查询 Native 支付
		    // '_action' => 'combine', // 查询合单支付
		];
	}
	// 预留支付接口
	public function pays(){
		// return url();
		if(request()->isPost()){
		$orderid= request()->param('orderid');//获取订单
		$info=Db::name('orderlist')->where(['ordernum'=>$orderid])->find();
		$productname=Db::name('schoolproduct')->where(['id'=>$info['product_id']])->find();
		$user=$info['user_id'];
		$name=Db::name('product')->where(['id'=>$productname['product_id']])->find();
		$user=Db::name('member')->where(['id'=>$info['user_id']])->find();
		$openid=$user['openid'];
		$price=$info['price'];
		$config=payconfig();
		Pay::config($config);
		$order = [
		    'out_trade_no' => $orderid,
		    'description' =>  (is_array($name) && isset($name['name'])) ? $name['name'] : '',
		    'amount' => [
		        'total' =>$price*100, 
		        'currency' => 'CNY',
		    ],
		    'payer' => [
		        'openid' => $openid,
		    ]
		];
		
		$result = Pay::wechat()->mini($order);
		return json(['code'=>200,'msg'=>'获取成功','data'=>$result]);
		}else{
			return json(['code'=>400,'msg'=>'请求方式错误']);
		}
		
	}
	// 订单支付状态更新
	public function orderstatus(){
		$orderid= request()->param('orderid');//获取订单
		$status= request()->param('status');//获取订单
		$info=Db::name('orderlist')->where(['ordernum'=>$orderid])->update(['paystatus'=>$status,'pay_time'=>TimeHelper::getTimestamp()]);
		if($info){
			return json(['code'=>200,'msg'=>'支付成功']);
		}else{
			return json(['code'=>400,'msg'=>'支付失败']);
		}
		
	}
	// 生成订单号并提交
	public function createOrder(){
		if(request()->isPost()){
		    $data= request()->param();
			// 未支付
			$data['paystatus']=0;
			$data['create_time']=TimeHelper::getTimestamp();
			// 生成订单
			$data['ordernum']=setorderid();
			Db::name('orderlist')->insert($data);
			return json(['code'=>200,'msg'=>'提交成功','data'=>$data]);
		}else{
			return json(['code'=>400,'msg'=>'请求方式错误']);
		}
	}
	// 获取未支付订单列表
  public function orderlist(){
	    $userid= request()->param('userid');
		// $typeid=request()->param('typeid')?request()->param('typeid'):1;
		$schoolid=request()->param('platform_id');
		if($schoolid){
			$data=Db::name('orderlist')
				->alias('a')
				->join('schoolproduct b','b.id=a.product_id')
				->join('product c','c.id=b.product_id')
				->join('useraddress d','d.id=a.address_id')
				->where(['a.user_id'=>$userid,'a.paystatus'=>0])
				->where('a.platform_id','in',[2,$schoolid])
				->order('a.create_time desc')
				->field('a.*,c.name,c.image,d.detail as address')
				->select()
				->toArray();
		}else{
		$data=Db::name('orderlist')
			->alias('a')
			->join('schoolproduct b','b.id=a.product_id')
			->join('product c','c.id=b.product_id')
			->join('useraddress d','d.id=a.address_id')
			->where(['a.user_id'=>$userid,'a.paystatus'=>0,'a.platform_id'=>2])
			->order('a.create_time desc')
			->field('a.*,c.name,c.image,d.detail as address')
			->select()
			->toArray();
		}
	
		foreach($data as $k=>$v){
			if (!isHttpsUrlByRegex($v['image'])) {
			    $data[$k]['image']=imgurl($v['image']);
			}
		}
		return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
  }
  // 取消订单
  public function cancelOrder(){
	  if(request()->isPost()){
	    $orderid= request()->param('id');
		$user_id= request()->param('user_id');
		$info=Db::name('orderlist')->where(['id'=>$orderid,'user_id'=>$user_id])->delete();
		if($info){
			return json(['code'=>200,'msg'=>'取消成功']);
		}else{
			return json(['code'=>400,'msg'=>'取消失败']);
		}
	}else{
			return json(['code'=>400,'msg'=>'请求方式错误']);
	}
  }
  // 获取未发货订单
  public function ordersend(){
	        $userid= request()->param('userid');
	  		// $typeid=request()->param('typeid')?request()->param('typeid'):1;
			$schoolid=request()->param('platform_id');
			if($schoolid){
			$data=Db::name('orderlist')
			->alias('a')
			->join('schoolproduct b','b.id=a.product_id')
			->join('product c','c.id=b.product_id')
			->join('useraddress d','d.id=a.address_id')
			->where(['a.user_id'=>$userid,'a.paystatus'=>1,'a.deliver_status'=>0])
			->where('a.platform_id','in',[2,$schoolid])
			->order('a.create_time desc')
			->field('a.*,c.name,c.image,d.detail as address')
			->select()
			->toArray();	
			}else{
	  		$data=Db::name('orderlist') 
	  		->alias('a')
	  		->join('schoolproduct b','b.id=a.product_id')
	  		->join('product c','c.id=b.product_id')
	  		->join('useraddress d','d.id=a.address_id')
	  		->where(['a.user_id'=>$userid,'a.paystatus'=>1,'a.deliver_status'=>0,'a.platform_id'=>2])
	  		->order('a.create_time desc')
	  		->field('a.*,c.name,c.image,d.detail as address')
	  		->select()
	  		->toArray();
			}
	  		foreach($data as $k=>$v){
	  			if (!isHttpsUrlByRegex($v['image'])) {
	  			    $data[$k]['image']=imgurl($v['image']);
	  			}
	  		} 
	  		return json(['code'=>200,'msg'=>'获取成功','data'=>$data]);
  }  
  // 获取已发货订单
  public function orderfinsh(){
	  $userid= request()->param('userid');
	  $data=Db::name('orderlist')
	  ->alias('a')
	  ->join('schoolproduct b','b.id=a.product_id')
	  ->join('product c','c.id=b.product_id')
	  ->join('useraddress d','d.id=a.address_id')
	  ->where(['a.user_id'=>$userid,'a.paystatus'=>1,'a.deliver_status'=>1])
	  ->where('a.state','<>',3)
	  ->order('a.create_time desc')
	  ->field('a.*,c.name,c.image,d.detail as address')
	  ->select()
	  ->toArray();
	  foreach($data as $k=>$v){
	  	if (!isHttpsUrlByRegex($v['image'])) {
	  	    $data[$k]['image']=imgurl($v['image']);
	  	}
		// 判断是快递
		if($v['delivery_type']==1){
			$user=Db::name('useraddress')->where(['id'=>$v['address_id']])->find();
			$lastFour = substr($user['phone'], -4);
			$data[$k]['delivery']=json_decode(getOrderTracesByJson($v['deliverorder'],$lastFour),true);
		}
		
	  } 
	  return json(['code'=>200,'msg'=>'获取成功','data'=>$data]); 
  }
}
